package com.cqc.manage.interceptor;

import com.cqc.manage.dto.PayloadDto;
import com.cqc.manage.error.tokenerror.TokenException;
import com.cqc.manage.repositories.UserRepositories;
import com.cqc.manage.token.JwtTokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * token认证
 */
public class AuthInterceptor implements HandlerInterceptor {
    private static Logger LOG = LoggerFactory.getLogger(AuthInterceptor.class);
    @Autowired
    private JwtTokenService jwtTokenService;
    @Autowired
    private UserRepositories userRepositories;

    /**
     * 请求处理之后
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // TODO Auto-generated method stub
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

    /**
     * 请求处理之后调用
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        // TODO Auto-generated method stub
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * 请求处理之前
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (request.getMethod().equals("OPTIONS")) return true;
        String authHeader = request.getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer:")){
            throw new TokenException(202,"没有token");
//            LOG.error("没有token");
        }
        // 获取token
        String token = authHeader.substring(7);
        // 验证token
        PayloadDto test = jwtTokenService.verifyTokenByHMAC(token);
        // 未完
        if (userRepositories.findUserByUserAccount(test.getUserName()) != null){
            return true;
        }
        return false;
    }
}
